import Axios from 'axios'
import Func from '../utils/func'
const configs = process.env;

const axios = Axios.create({
  timeout: 0,
});

//添加一个请求拦截器
axios.interceptors.request.use(request => {
  const pathname = location.pathname.replace(/\//g, "") || "pc";
  request.headers.common['Platform'] = pathname;
  request.headers.common['tenantCode'] = sessionStorage.tenantCode || "1";
  const token = Func.getToken() || "";
  request.headers.common['Authorization'] = token;
  return request;
})

// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = [];

let refreshNumer = 0;

// 添加一个响应拦截器
axios.interceptors.response.use(response => {
  //OSS
  if (response.headers.etag && !response.data) {
    response.data = response.headers;
  }
  return response;
}, function (error) {
  if (error.response.status == 401) {
    const config = error.config;
    if (refreshNumer > 1) {
      refreshNumer = 0;
      return;
    };
    if (!isRefreshing) {
      isRefreshing = true;
      return refreshToken().then(res => {
        refreshNumer++;
        isRefreshing = false;
        const { token } = res.response;
        let userInfo = Func.getUserInfo();
        userInfo.token = token;
        Func.setSession("userInfo", userInfo);
        const pathname = location.pathname.replace(/\//g, "") || "pc";
        if (pathname == "mb") {
          Func.setCookie("userInfo", {
            id: userInfo.id,
            token: userInfo.token,
            token_type: userInfo.token_type,
            openId: userInfo.openId,
            tenantCode: userInfo.tenantCode,
          });
        }
        // 已经刷新了token，将所有队列中的请求进行重试
        requests.forEach(cb => cb(Func.getToken()));
        requests = [];
        config.headers['Authorization'] = Func.getToken();
        return axios(config)
      }).catch(res => {
        isRefreshing = false;
        console.error('refreshtoken error =>', res);
        loginOut();
      })
    } else {
      // 正在刷新token，将返回一个未执行resolve的promise
      return new Promise(resolve => {
        // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
        requests.push(token => {
          config.headers['Authorization'] = token;
          resolve(axios(config));
        })
      })
    }
  }
  return Promise.reject(error);
});

function loginOut() {
  Func.removeSession("userInfo");
  Func.removeCookie("userInfo");
  location.href = location.href;
}

//刷新oken
function refreshToken() {
  let token = Func.getUserInfo().token;
  if (token) {
    return axios.get(configs.main + '/api/Login/RefreshToken', { params: { token } }).then(res => res.data);
  } else {
    return "";
  }
}

export default {
  axios: axios,
  configs: configs
}
